<template>
	<div>
		<transition name="toast">
			<div class="toast-wrap" id="toastWrap" v-if="toast">
				<p class="toast-content" v-html="msg"></p>
			</div>
		</transition>
	</div>
	
</template>

<script>
	export default{
		name:"toastWrap",
		data(){
			return{
				msg:"",
				time:3000,
				toast:false,
				toastTimer:null
			}
		},
		mounted(){
			let that = this;
			/*msg可以是一个对象,两个参数，一个是showTime,另外一个msg*/
			this.$root.$on('toast',(obj)=>{
				obj.msg = obj.msg || that.msg ;
				obj.showTime = obj.showTime || that.time ;
				this.toastShowHide(obj.msg,obj.showTime)
			})
		},
		methods:{
			toastShowHide(msg="",showTime=3000){
				let that= this;
				if(that.toastTimer){
					clearTimeout( that.toastTimer )
				}
				that.msg = msg;
				that.toast = true;
				that.toastTimer = setTimeout(function(){
					if( that.toastTimer ){
						clearTimeout( that.toastTimer )
					}
					that.toast = false;
				},showTime)
			}
		}
		
	}
</script>

<style scoped="scoped">
	/*用帧动画实现定时器效果*/
	.toast-wrap{
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		margin: auto;
		width: 100%;
		height: 0;
		z-index: 1070;
	}
	.toast-content{
		position: relative;
		display: block;
		margin: auto;
		padding: .05rem .15rem;
		border-radius: 10px;
		color: #fff;
		background-color: rgba(0,0,0,.5);
		text-align: center;
		max-width: 50%;
	}
	.toast-enter,.toast-leave{
		opacity: 0;
	}
	.toast-leave-active,.toast-enter-active{
		transition: opacity .5s;
	}
	/*.toast-wrap{
		-webkit-animation: toastShowHide 4s 1;
		-moz-animation: toastShowHide 4s 1;
		-ms-animation: toastShowHide 4s 1;
		animation: toastShowHide 4s 1;
	}	
	@keyframe toastShowHide{
		0%{
			opacity: 0;
		}
		12.5%{
			opacity: 1;
		}
		87.5%{
			opacity: 1;
		}
		100%{
			opacity: 0;
		}
	}*/
</style>